package com.crm.config.security;

import cn.hutool.core.lang.Console;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crm.commons.DataEnum;
import com.crm.entity.CrmUser;
import com.crm.mapper.CrmUserMapper;
import com.crm.vo.MySecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author junxian.dou
 * @Package：com.crm.config
 * @Project：springboot-crm
 * @name：SecurityConfig
 * @Date：2024/11/25 11:32
 * @Filename：SecurityConfig
 * @verson 1.0.0
 * @desc
 */

@Slf4j
public class DBUserDetailsManager implements UserDetailsService {

    @Resource
    private CrmUserMapper userMapper;

    //根据用户名匹配密码
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<CrmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CrmUser::getName, username);
        CrmUser crmUser = userMapper.selectOne(wrapper);
        log.info("查询用户信息{}", username);
        if (Objects.isNull(crmUser)) {
            throw new UsernameNotFoundException(username);
        } else {
            List<String> userPermissions = userMapper.getAuthorityByUserId(crmUser.getId());
            List<GrantedAuthority> authorities = userPermissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
            return new MySecurityUser(crmUser, authorities);
        }
    }

}
